package org.club.Service.impl;

import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.club.Service.AdminInfoService;
import org.club.Service.FileOssService;
import org.club.common.model.dto.*;
import org.club.common.model.vo.*;
import org.club.common.util.EmailUtils;
import org.club.mapper.ActivityMapper;
import org.club.mapper.AdminInfoMapper;
import org.club.common.model.entity.ClubInfo;
import org.club.common.model.entity.BusinessException;
import org.club.common.model.entity.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AdminInfoImpl implements AdminInfoService {
    @Autowired
    private AdminInfoMapper adminInfoMapper;
    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private FileOssService fileOssService;
    @Autowired
    private EmailUtils emailUtils;

    //分页查询用户信息
    @Override
    public List<UserInfoVO> getUserClubInfoList(UserInfoDto userInfoDto) {
        // 参数校验
        if (userInfoDto == null || userInfoDto.getPageNum() <= 0 || userInfoDto.getPageSize() <= 0) {
            throw new IllegalArgumentException("参数无效：pageNum 和 pageSize 必须大于 0");
        }

        try {
            // 开始分页
            PageHelper.startPage(userInfoDto.getPageNum(), userInfoDto.getPageSize());

            // 查询数据
            List<UserInfo> userInfoList = adminInfoMapper.listUserClubInfo(
                    userInfoDto.getRealName(),
                    userInfoDto.getIdCard()
            );
            log.info("查询到用户信息：{}", userInfoList);
            List<UserInfoVO> userInfoVOList;
            if (userInfoList != null && !userInfoList.isEmpty()) {
                userInfoVOList = userInfoList.stream()
                        .map(UserInfoVO::new)
                        .toList();
            } else {
                userInfoVOList = Collections.emptyList();
            }
            log.info("转换后的用户信息：{}", userInfoVOList);
            return userInfoVOList;
        } catch (Exception e) {
            throw new BusinessException(400, "查询用户信息失败");
        }
    }

    // 分页查询社团信息
    @Override
    public List<ClubInfoVO> getClubInfolist(ClubInfoDto clubInfoDto) {
        // 参数校验
        if (clubInfoDto == null || clubInfoDto.getPageNum() <= 0 || clubInfoDto.getPageSize() <= 0) {
            throw new IllegalArgumentException("参数无效：pageNum 和 pageSize 必须大于 0");
        }

        try {
            // 开始分页
            PageHelper.startPage(clubInfoDto.getPageNum(), clubInfoDto.getPageSize());

            // 查询数据
            List<ClubInfo> clubInfoList = adminInfoMapper.listClubInfo(
                    clubInfoDto.getName(),
                    clubInfoDto.getStatus()
            );
            List<ClubInfoVO> clubInfoVOlist;
            if (clubInfoList != null && !clubInfoList.isEmpty()) {
                clubInfoVOlist = clubInfoList.stream()
                        .map(ClubInfoVO::new)
                        .toList();
            } else {
                clubInfoVOlist = Collections.emptyList();
            }

            return clubInfoVOlist;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(400, "查询社团信息失败");
        }
    }

    @Override
    @Transactional
    public void deleteUser(Long userId, String username) {
        if (userId == null || username == null) {
            throw new BusinessException(400, "信息缺失");
        }
        Integer i = adminInfoMapper.deleteUser(userId, username);
        if (i == 0) {
            throw new BusinessException(400, "删除失败");
        }
    }

    @Override
    public String getClubAdmin(Long userId) {
        //验证该用户是否为社团管理员
        String clubName = adminInfoMapper.setClubsAdmin(userId);
        if (clubName == null) {
            throw new BusinessException(400, "该用户不是社团管理员");
        }
        return clubName;
    }

    @Override
    public void setUserstatus(Long userId, String status) {
        if (userId == null || status == null) {
            throw new BusinessException(400, "信息缺失");
        }
        if (!status.equals("0") && !status.equals("1")) {
            throw new BusinessException(400, "状态值错误");
        }
        Integer i = adminInfoMapper.setUserstatus(userId, status);
        if (i == 0) {
            throw new BusinessException(400, "修改失败");
        }
    }

    @Override
    public void setClubactivitystatus(Long clubId, String activity_status) {
        if (clubId == null || activity_status == null) {
            throw new BusinessException(400, "信息缺失");
        }
        if (!activity_status.equals("正常") && !activity_status.equals("暂停活动") && !activity_status.equals("已解散")) {
            throw new BusinessException(400, "状态值错误");
        }
        Integer i = adminInfoMapper.setClubactivitystatus(clubId, activity_status);
        if (i == 0) {
            throw new BusinessException(400, "修改失败");
        }
    }

    //查询用户总数
    @Override
    public Integer seletCount(UserInfoDto userClubInfoDto) {
        Integer i = adminInfoMapper.seletCount(userClubInfoDto.getIdCard(), userClubInfoDto.getRealName());
        return i;
    }

    //查询社团总数
    @Override
    public Integer seletClubCount(ClubInfoDto clubInfoDto) {
        Integer i = adminInfoMapper.seletClubCount(clubInfoDto.getStatus(), clubInfoDto.getName());
        return i;
    }

    //社团状态修改
    @Override
    public void setClubstatus(Long clubId, String status) {
        if (clubId == null || status == null) {
            throw new BusinessException(400, "信息缺失");
        }
        // 验证状态值是否合法（0-待审核，1-已通过，2-已拒绝）
        if (!status.equals("0") && !status.equals("1") && !status.equals("2")) {
            throw new BusinessException(400, "状态值错误");
        }
        try {
            adminInfoMapper.setClubstatus(clubId, status);
            //查询clubid对应的user_id
            Long user_id = adminInfoMapper.selectUserId(clubId);
            //查询user_id是否存在user_roles表，如果不存在则插入，存在则更新
            Integer integer = adminInfoMapper.selectUser_roles(user_id);
            log.info("user_id是否存在user_roles表：{}", integer);
            if (integer >= 0) {
                adminInfoMapper.UpdeateFileFromOss(user_id);
            } else {
                adminInfoMapper.Insertionuser_roles(user_id);
            }
            //查询出社团成员信息（邮箱、姓名）
            List<Map<String, String>> userInfos = activityMapper.getEmailAndName((Collections.singletonList(user_id)));
            log.info("查询出的社团成员信息：{}", userInfos);
            //发送邮件
            for (Map<String, String> userInfo : userInfos) {
                String name = userInfo.get("real_name");
                String email = userInfo.get("email");
                emailUtils.sendSimpleMail(email, "社团创建申请审核结果", name + "同学 您好，您的社团创建审核结果为:已通过,请登录社团平台查看详情。");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(400, "修改失败");
        }


    }

    //更新个人信息
    @Override
    public UserVo updatePersonalInfo(UpdatePersonalInfoRequestDto updatePersonalInfoRequestDto, MultipartFile file) {
        if (updatePersonalInfoRequestDto.getUserId() == null) {
            throw new BusinessException(400, "用户ID不能为空");
        }
        //检查该用户是否存在
        Integer i = activityMapper.selectUser(updatePersonalInfoRequestDto.getUserId());
        if (i == 0) {
            throw new BusinessException(400, "用户不存在");
        }
        try {
            if (file != null) {
                //上传图片到OSS
                String s = fileOssService.uploadToOss(file);
                if (s != null) {
                    updatePersonalInfoRequestDto.setNewAvatarUrl(s);
                }
            }
            log.info("更新个人信息，用户ID: {}, 真实姓名: {}, 电话: {}, 邮箱: {}, 新头像地址: {}", updatePersonalInfoRequestDto.getUserId(),
                    updatePersonalInfoRequestDto.getRealName(), updatePersonalInfoRequestDto.getPhone(),
                    updatePersonalInfoRequestDto.getEmail(), updatePersonalInfoRequestDto.getNewAvatarUrl());
            Integer n = activityMapper.updatePersonalInfo(updatePersonalInfoRequestDto);
            if (n <= 0) {
                throw new BusinessException(500, "更新个人信息失败");
            }
            if (updatePersonalInfoRequestDto.getNewAvatarUrl() != null) {
                //最后删除OSS原始图片
                Boolean b = fileOssService.deleteFileFromOss(updatePersonalInfoRequestDto.getOriginalAvatarUrl());
                log.info("删除OSS原始图片，原始图片地址: {}", b);
            }
            //返回更新后的用户信息
            UserVo userVo = activityMapper.selectUserInfo(updatePersonalInfoRequestDto.getUserId());
            return userVo;
        } catch (Exception e) {
            e.printStackTrace();
            fileOssService.deleteFileFromOss(updatePersonalInfoRequestDto.getNewAvatarUrl());
            throw new BusinessException(500, "更新个人信息失败");
        }
    }

    @Override
    public ClubActivityResponseVO getClubActivity(ClubActivityDto clubActivityDto) {
        try {
            // 获取社团活动数据
            List<Map<String, Object>> clubActivityData = adminInfoMapper.getClubActivityData(
                    clubActivityDto.getStartDate(),
                    clubActivityDto.getEndDate()
            );

            // 获取活动趋势数据
            List<Map<String, Object>> trendData = adminInfoMapper.getActivityTrendData(
                    clubActivityDto.getStartDate(),
                    clubActivityDto.getEndDate()
            );

            // 计算活跃度分数
            List<ClubActivityVO> clubActivityList = new ArrayList<>();
            int totalActivity = 0;
            int maxActivity = 0;

            for (Map<String, Object> data : clubActivityData) {
                ClubActivityVO vo = new ClubActivityVO();
                vo.setClubId(((Number) data.get("clubId")).longValue());
                vo.setClubName((String) data.get("clubName"));
                vo.setEventCount(((Number) data.get("eventCount")).intValue());
                vo.setMemberCount(((Number) data.get("memberCount")).intValue());
                Object lastActivityTimeObj = data.get("lastActivityTime");
                if (lastActivityTimeObj != null) {
                    if (lastActivityTimeObj instanceof java.sql.Timestamp timestamp) {
                        vo.setLastActivityTime(timestamp.toLocalDateTime());
                    } else if (lastActivityTimeObj instanceof java.util.Date date) {
                        vo.setLastActivityTime(date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                    } else if (lastActivityTimeObj instanceof LocalDateTime localDateTime) {
                        vo.setLastActivityTime(localDateTime);
                    } else {
                        log.warn("lastActivityTime 意外类型: {}", lastActivityTimeObj.getClass().getName());
                    }
                }



                // 计算活跃度分数 (活动数 * 30 + 成员数 * 10)
                int activityScore = vo.getEventCount() * 30 + vo.getMemberCount() * 10;
                vo.setActivityScore(activityScore);

                totalActivity += activityScore;
                maxActivity = Math.max(maxActivity, activityScore);

                clubActivityList.add(vo);
            }

            // !!! 添加排序逻辑 !!!
            // 按照 activityScore 降序排序
            clubActivityList.sort(Comparator.comparingInt(ClubActivityVO::getActivityScore).reversed());

            // 计算平均活跃度
            double averageActivity = clubActivityList.isEmpty() ? 0 :
                    (double) totalActivity / clubActivityList.size();

            // 转换趋势数据
            List<ClubActivityTrendVO> trendVOList = trendData.stream()
                    .map(data -> {
                        ClubActivityTrendVO trendVO = new ClubActivityTrendVO();
                        // 假设数据库返回的日期是java.sql.Date或其他可以通过toString()获取YYYY-MM-DD格式的类型
                        trendVO.setDate(data.get("date").toString());
                        trendVO.setValue(((Number) data.get("count")).intValue());
                        return trendVO;
                    })
                    .collect(Collectors.toList());

            // 构建响应对象
            ClubActivityResponseVO response = new ClubActivityResponseVO();
            response.setTotalActivity(totalActivity);
            response.setAverageActivity(averageActivity);
            response.setMaxActivity(maxActivity);
            response.setClubActivityList(clubActivityList);
            response.setTrendData(trendVOList);

            return response;
        } catch (Exception e) {
            log.error("获取社团活跃度数据失败", e);
            // 抛出业务异常，让Controller层处理
            throw new BusinessException(500, "获取社团活跃度数据失败");
        }
    }
}
